﻿using System;
using System.Linq;
using System.Windows.Forms;
using ChatClient.Utility;
using Timer = System.Windows.Forms.Timer;

namespace ChatClient
{
    public partial class FrmClient : Form
    {
        private readonly MessageStream _messageStream;
        private readonly Timer _timer;
        private String _userName;
        private int _userId;
        private String _chatMessage;
        private String _forumMessage;

        public FrmClient()
        {
            InitializeComponent();

            _messageStream = new MessageStream();
            _messageStream.HandleResponse += MessageStreamHandleResponse;
            _messageStream.Start();

            _timer = new Timer { Interval = 2000 };
            _timer.Tick += TimerTick;

            tabControl1.SelectedIndexChanged += new EventHandler(TabControl1SelectedIndexChanged);
        }

        void MessageStreamHandleResponse(string message)
        {
            if (message.StartsWith("LOGGEDIN"))
            {
                var delim = message.IndexOf('|');
                _userName = message.Substring(8, delim - 8);
                _userId = Int32.Parse(message.Substring(delim + 1));
                BeginInvoke((MethodInvoker)(() => textBox1.Clear()));
                _timer.Start();
            }

            else if (message.StartsWith("LOGGEDOUT"))
            {
                BeginInvoke((MethodInvoker)(() => textBox1.AppendText("User name: " + message.Substring(9) + " has logged out...")));
            }

            else if (message.StartsWith("USEREXISTS"))
            {
                BeginInvoke((MethodInvoker)(() => textBox1.AppendText("User name: " + message.Substring(10) + " exists. Please choose a different user name")));
            }

            else if (message.StartsWith("CHAT"))
            {
                var delim = message.IndexOf('|');
                var chatMessageSender = message.Substring(4, delim - 4);
                var chatMessage = message.Substring(delim + 1);

                BeginInvoke((MethodInvoker)(() => textBox1.AppendText(chatMessageSender + " : " + chatMessage + Environment.NewLine)));
            }

            else if (message.StartsWith("USERS"))
            {
                var users = message.Substring(5);
                var userArray = users.Split(',');

                foreach (var user in userArray.Where(s => !s.Equals("")))
                {
                    if (user != null && user != _userName)
                    {
                        var temp = user;
                        BeginInvoke((MethodInvoker) (() => checkedListBox1.Items.Add(temp)));
                    }
                }
            }

            else if (message.StartsWith("FORUMUSERS"))
            {
                var forumUsers = message.Substring(10);
                var forumUserArray = forumUsers.Split(',');

                foreach (var forumUser in forumUserArray.Where(s => !s.Equals("")))
                {
                    if (forumUser != null && forumUser != _userName)
                    {
                        var temp = forumUser;
                        BeginInvoke((MethodInvoker)(() => checkedListBox2.Items.Add(temp)));
                    }
                }
            }

            else if (message.StartsWith("QUERY"))
            {
                var messages = message.Substring(5);
                var messageArray = messages.Split('~');

                foreach (var item in messageArray)
                {
                    if (item.StartsWith("OTHERUSERLOGGEDIN"))
                    {
                        var otherUser = item.Substring(17);

                        BeginInvoke((MethodInvoker)(() => textBox1.AppendText(otherUser + " has logged in..." + Environment.NewLine)));
                    } 
                    
                    else if (item.StartsWith("OTHERUSERCHAT"))
                    {
                        var delim = item.IndexOf('|');
                        var otherUser = item.Substring(13, delim - 13);
                        var otherUsersMessage = item.Substring(delim + 1);

                        BeginInvoke((MethodInvoker)(() => textBox1.AppendText(otherUser + " : " + otherUsersMessage + Environment.NewLine)));
                    }

                    else if (item.StartsWith("OTHERUSERLOGGEDOUT"))
                    {
                        var otherUser = item.Substring(18);

                        BeginInvoke((MethodInvoker)(() => textBox1.AppendText(otherUser + " has logged out..." + Environment.NewLine)));
                    }

                    else if (item.StartsWith("REQPRIVATECHAT"))
                    {
                        var delim = item.IndexOf('|');
                        var requestingUser = item.Substring(14, delim - 14);

                        BeginInvoke((MethodInvoker)(() => textBox1.AppendText(requestingUser + " requests a private chat with you..." + Environment.NewLine)));
                    }
                }
            }

            else if (message.StartsWith("FORUMS"))
            {
                var forums = message.Substring(6);
                var forumDetails = forums.Split(',');

                foreach (var forum in forumDetails.Where(s => !s.Equals("")))
                {
                    var temp = forum.Replace(" ~ ", Environment.NewLine);
                    BeginInvoke((MethodInvoker)(() => textBox3.AppendText(temp + Environment.NewLine)));
                }
            }
        }

        void TimerTick(object sender, EventArgs e)
        {
            _messageStream.SendMessage("QUERY_SERVER" + _userName);
            textBox3.Clear();
            _messageStream.SendMessage("GETFORUMS");
        }

        private void BtnLogIn(object sender, EventArgs e)
        {
            LogIn();
        }

        void LogIn()
        {
            _userName = textBox4.Text;
            _messageStream.SendMessage("LOGIN" + _userName);
            button1.Enabled = true;
            button3.Enabled = true;
            textBox2.Enabled = true;
        }

        private void BtnSendChatMessage(object sender, EventArgs e)
        {
            _chatMessage = textBox2.Text;
            _messageStream.SendMessage("CHAT" + _userName + "|" + _chatMessage);
            textBox2.Clear();
        }

        private void TextBox2Click(object sender, EventArgs e)
        {
            textBox2.Clear();
        }

        private void TextBox4Click(object sender, EventArgs e)
        {
            textBox4.Clear();
        }

        private void TextBox5Click(object sender, EventArgs e)
        {
            textBox5.Clear();
        }

        private void FrmClientFormClosed(object sender, FormClosedEventArgs e)
        {
            _messageStream.SendMessage("LOGOUT" + _userName + "|" + _userId);
        }

        private void BtnGetLoggedInUsers(object sender, EventArgs e)
        {
            checkedListBox1.Items.Clear();
            _messageStream.SendMessage("GETUSERNAMES");
            checkedListBox1.Enabled = true;
            button4.Enabled = true;
        }

        private void BtnSendPrivateChatRequest(object sender, EventArgs e)
        {
            var requestedUser = checkedListBox1.SelectedItem;
            _messageStream.SendMessage("REQUESTPRIVATECHAT" + _userName + "|" + requestedUser);
        }

        private void BtnGetLoggedInForumUsers(object sender, EventArgs e)
        {
            checkedListBox2.Items.Clear();
            _messageStream.SendMessage("GETFORUMUSERNAMES");
            checkedListBox2.Enabled = true;
        }

        private void TabControl1SelectedIndexChanged(object sender, EventArgs e)
        {
            textBox3.Clear();
            _messageStream.SendMessage("GETFORUMS");
        }

        private void BtnPostForumMessage(object sender, EventArgs e)
        {
            _forumMessage = textBox5.Text;
            _messageStream.SendMessage("POSTFORUMMESSAGE" + _forumMessage + "|" + _userName);
            textBox5.Clear();
            textBox3.Clear();
            _messageStream.SendMessage("GETFORUMS");
        }
    }
}
